package com.huiminpay.merchant.service;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.domain.BusinessCast;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.convert.AppCovert;
import com.huiminpay.merchant.convert.MerchantConvent;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.entity.Merchant;
import com.huiminpay.merchant.mapper.AppMapper;
import com.huiminpay.merchant.mapper.MerchantMapper;
import com.yh.huiminpay.merchant.api.AppService;
import com.yh.huiminpay.merchant.dto.AppDTO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

/**
 *  支付参数配置实现类
 */
@Service
public class AppServiceImpl implements AppService  {
    //需要跟数据库打交道
    @Autowired
    AppMapper appMapper;

    //用户创建应用现看用户是否资质认证
    @Autowired
    MerchantMapper merchantMapper;

   //商户应用实现方法
    @Override
    public AppDTO createApp(AppDTO app) {
        //检测必要字段
        if(app == null || app.getMerchantId( )== null
                      || app.getMerchantId() == 0
                      || StringUtils.isEmpty(app.getAppName())){
            BusinessCast.cast(CommonErrorCode.E_200223);

        }
        //查看商户资质审核是否通过，通过之后创建应用
        Merchant merchant=merchantMapper.selectById(app.getMerchantId());
        if(merchant == null || !merchant.getAuditStatus().equals("2")){
            BusinessCast.cast(CommonErrorCode.E_200223);
        }
        //根据应用名称查询应用信息，如果有说明存在
       Integer integer= appMapper.selectCount(new LambdaQueryWrapper<App>().eq(App::getAppName,app.getAppName()));
        if(integer>0){
            BusinessCast.cast(CommonErrorCode.E_200225 );
        }
        App apu=AppCovert.INSTANCEE.dto2entity(app);
        apu.setAppId(UUID.randomUUID().toString());
        appMapper.insert(apu);
        return AppCovert.INSTANCEE.entity2dto(apu);
    }
    /**
     \* 查询商户下的应用列表
     \* @param merchantId
     \* @return
     */
    @Override
    public List<AppDTO> queryAppByMerchant(Long merchantId) throws BusinessException {
        List<App> apps = appMapper.selectList(new QueryWrapper<App>().lambda().eq(App::getMerchantId,merchantId));
        List<AppDTO> appDTOS = AppCovert.INSTANCEE.listentity2dto(apps);
        return appDTOS;
    }

    /**
     \* 根据业务id查询应用
     \* @param id
     \* @return
     */
    @Override
    public AppDTO getAppById(String id) throws BusinessException {
        App app = appMapper.selectOne(new QueryWrapper<App>().lambda().eq(App::getAppId, id));
        return AppCovert.INSTANCEE.entity2dto(app);
    }
}
